<template>
  <div class="student-exceptions">
    <el-card class="exception-card">
      <template #header>
        <div class="card-header">
          <h3>异常处理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="scanDirectory">
              <el-icon><refresh /></el-icon> 扫描目录
            </el-button>
          </div>
        </div>
      </template>

      <el-form :model="form" label-width="120px" class="scan-form">
        <el-form-item label="报告目录">
          <el-input v-model="form.directory" placeholder="请选择实验报告目录">
            <template #append>
              <el-button @click="showDirectorySelector = true">
                <el-icon><folder-opened /></el-icon> 选择
              </el-button>
            </template>
          </el-input>

          <!-- 文件系统目录选择器组件 -->
          <file-system-directory-selector
            v-model="showDirectorySelector"
            :initial-path="form.directory"
            @select="handleDirectorySelected"
            @cancel="showDirectorySelector = false"
          />
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeTab" class="exception-tabs">
        <el-tab-pane label="文件名不合规" name="invalidFormat">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="exceptions.invalidFormat.length === 0" class="empty-container">
            <el-empty description="没有发现文件名不合规的异常" />
          </div>
          <div v-else>
            <el-table :data="exceptions.invalidFormat" border style="width: 100%">
              <el-table-column prop="name" label="文件名" min-width="200" />
              <el-table-column prop="path" label="文件路径" min-width="300" show-overflow-tooltip />
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleRename(scope.row)"
                    :icon="Edit"
                    circle
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="学生不在名单中" name="unknownStudent">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="exceptions.unknownStudent.length === 0" class="empty-container">
            <el-empty description="没有发现学生不在名单中的异常" />
          </div>
          <div v-else>
            <el-table :data="exceptions.unknownStudent" border style="width: 100%">
              <el-table-column label="文件名" min-width="200">
                <template #default="scope">
                  {{ scope.row.name || (scope.row.file && scope.row.file.name) }}
                </template>
              </el-table-column>
              <el-table-column label="学号" width="120">
                <template #default="scope">
                  {{ scope.row.parsedInfo && scope.row.parsedInfo.studentId }}
                </template>
              </el-table-column>
              <el-table-column label="姓名" width="120">
                <template #default="scope">
                  {{ scope.row.parsedInfo && scope.row.parsedInfo.studentName }}
                </template>
              </el-table-column>
              <el-table-column label="文件路径" min-width="300" show-overflow-tooltip>
                <template #default="scope">
                  {{ scope.row.path || (scope.row.file && scope.row.file.path) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="handleAddStudent(scope.row)"
                  >
                    添加到名单
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 重命名文件对话框 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名文件"
      width="500px"
    >
      <el-form :model="renameForm" :rules="renameRules" ref="renameFormRef" label-width="100px">
        <el-form-item label="原文件名">
          <el-input v-model="renameForm.oldName" disabled />
        </el-form-item>
        <el-form-item label="新文件名" prop="newName">
          <el-input v-model="renameForm.newName" />
        </el-form-item>
        <el-form-item label="文件格式提示" class="format-hint">
          <div>正确格式：实验X_学号X_姓名X.doc</div>
          <div>例如：实验1_2021001_张三.doc</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRename">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加学生对话框 -->
    <el-dialog
      v-model="addStudentDialogVisible"
      title="添加学生到名单"
      width="500px"
    >
      <el-form :model="studentForm" :rules="studentRules" ref="studentFormRef" label-width="80px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="studentForm.grade" placeholder="请选择年级" style="width: 100%">
            <el-option
              v-for="year in gradeOptions"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="studentForm.major" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addStudentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddStudent">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Refresh, FolderOpened, Edit } from '@element-plus/icons-vue'
import FileSystemDirectorySelector from '@/components/FileSystemDirectorySelector.vue'
import logger from '@/utils/Logger'

export default {
  name: 'StudentExceptions',
  components: {
    Refresh,
    FolderOpened,
    FileSystemDirectorySelector
  },
  setup() {
    const store = useStore()
    const loading = ref(false)
    const activeTab = ref('invalidFormat')
    const renameDialogVisible = ref(false)
    const addStudentDialogVisible = ref(false)
    const renameFormRef = ref(null)
    const studentFormRef = ref(null)
    const showDirectorySelector = ref(false)

    const form = reactive({
      directory: ''
    })

    const exceptions = reactive({
      invalidFormat: [],
      unknownStudent: []
    })

    const renameForm = reactive({
      oldName: '',
      newName: '',
      path: ''
    })

    const studentForm = reactive({
      studentId: '',
      name: '',
      grade: '',
      major: ''
    })

    const renameRules = {
      newName: [
        { required: true, message: '请输入新文件名', trigger: 'blur' },
        {
          pattern: /^实验(\d+|[一二三四五六七八九十]+)_(\w+)_(.+)\.(doc|docx|pdf|txt)$/,
          message: '文件名格式不正确，应为：实验X_学号X_姓名X.doc',
          trigger: 'blur'
        }
      ]
    }

    const studentRules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { pattern: /^\d{5,12}$/, message: '学号必须为5-12位数字', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
      ],
      grade: [
        { required: true, message: '请选择年级', trigger: 'change' }
      ],
      major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
      ]
    }

    // 年级选项（当前年份-10年 到 当前年份+1年）
    const currentYear = new Date().getFullYear()
    const gradeOptions = Array.from({ length: 12 }, (_, i) => (currentYear - 10 + i).toString())

    // 计算属性
    const students = computed(() => store.state.students || [])

    // 方法
    // 打开目录选择器对话框
    const handleSelectDirectory = async () => {
      console.log('StudentExceptions: 打开目录选择器对话框');
      showDirectorySelector.value = true;
      console.log('StudentExceptions: showDirectorySelector =', showDirectorySelector.value);
    }

    // 处理目录选择
    const handleDirectorySelected = (path) => {
      console.log('StudentExceptions: 目录选择回调被触发，path =', path);
      if (path) {
        form.directory = path;
        ElMessage.success('已选择目录: ' + path);
        logger.info('目录选择成功', { path });
      }
      showDirectorySelector.value = false;
      console.log('StudentExceptions: 目录选择完成，showDirectorySelector =', showDirectorySelector.value);
    }

    const scanDirectory = async () => {
      if (!form.directory) {
        ElMessage.warning('请先选择实验报告目录')
        return
      }

      loading.value = true
      try {
        // 调用后端API扫描目录
        const result = await store.dispatch('scanReportDirectory', {
          directoryPath: form.directory
        })

        if (result && result.exceptions) {
          exceptions.invalidFormat = result.exceptions.invalidFormat || []
          exceptions.unknownStudent = result.exceptions.unknownStudent || []

          const totalExceptions = exceptions.invalidFormat.length + exceptions.unknownStudent.length

          if (totalExceptions > 0) {
            ElMessage.warning(`扫描完成，发现 ${totalExceptions} 个异常`)
            logger.warn(`扫描目录完成，发现 ${totalExceptions} 个异常`)
          } else {
            ElMessage.success('扫描完成，未发现异常')
            logger.info('扫描目录完成，未发现异常')
          }
        } else {
          ElMessage.warning('扫描结果为空')
        }
      } catch (error) {
        logger.error('扫描目录失败', error)
        ElMessage.error('扫描目录失败：' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

    const handleRename = (file) => {
      renameForm.oldName = file.name
      renameForm.newName = file.name
      renameForm.path = file.path
      renameDialogVisible.value = true
    }

    const submitRename = async () => {
      if (!renameFormRef.value) return

      await renameFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 调用后端API重命名文件
            await store.dispatch('renameFile', {
              oldPath: renameForm.path,
              newName: renameForm.newName
            })

            logger.info(`重命名文件: ${renameForm.oldName} -> ${renameForm.newName}`)
            ElMessage.success('文件重命名成功')

            // 从异常列表中移除
            const index = exceptions.invalidFormat.findIndex(f => f.path === renameForm.path)
            if (index !== -1) {
              exceptions.invalidFormat.splice(index, 1)
            }

            renameDialogVisible.value = false
          } catch (error) {
            logger.error('重命名文件失败', error)
            ElMessage.error('重命名文件失败：' + (error.message || '未知错误'))
          }
        }
      })
    }

    const handleAddStudent = (exception) => {
      if (exception.parsedInfo) {
        studentForm.studentId = exception.parsedInfo.studentId || ''
        studentForm.name = exception.parsedInfo.studentName || ''
        studentForm.grade = new Date().getFullYear().toString() // 默认当前年份
        studentForm.major = ''
        addStudentDialogVisible.value = true
      } else {
        ElMessage.warning('无法解析学生信息')
      }
    }

    const submitAddStudent = async () => {
      if (!studentFormRef.value) return

      await studentFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 检查学号是否已存在
            const exists = students.value.some(s => s.studentId === studentForm.studentId)
            if (exists) {
              ElMessage.error('学号已存在')
              return
            }

            await store.dispatch('addStudent', { ...studentForm })
            ElMessage.success('学生添加成功')
            logger.info(`成功添加学生: ${studentForm.name} (${studentForm.studentId})`)

            // 从异常列表中移除
            const index = exceptions.unknownStudent.findIndex(
              e => e.parsedInfo.studentId === studentForm.studentId
            )
            if (index !== -1) {
              exceptions.unknownStudent.splice(index, 1)
            }

            addStudentDialogVisible.value = false
          } catch (error) {
            logger.error('添加学生失败', error)
            ElMessage.error('添加学生失败：' + error.message)
          }
        }
      })
    }

    onMounted(() => {
      // 初始化时不自动扫描，等用户选择目录后手动扫描
    })

    return {
      loading,
      activeTab,
      form,
      exceptions,
      renameDialogVisible,
      addStudentDialogVisible,
      renameForm,
      renameFormRef,
      renameRules,
      studentForm,
      studentFormRef,
      studentRules,
      gradeOptions,
      showDirectorySelector,
      Edit,
      handleSelectDirectory,
      handleDirectorySelected,
      scanDirectory,
      handleRename,
      submitRename,
      handleAddStudent,
      submitAddStudent
    }
  }
}
</script>

<style scoped>
.student-exceptions {
  width: 100%;
}

.exception-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.scan-form {
  margin-bottom: 20px;
}

.exception-tabs {
  margin-top: 20px;
}

.loading-container,
.empty-container {
  padding: 20px 0;
}

.format-hint {
  color: #909399;
  font-size: 14px;
}
</style>
